//
//  AlumContentViewController.m
//  u76ho
//
//  Created by m-air-01 on 16/1/29.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "AlumContentViewController.h"
#import "AlumContentTableViewCell.h"
#import "ManagerAlumViewController.h"
#import "BoostViewController.h"
#import "SendPictureViewController.h"
@interface AlumContentViewController ()
<UITableViewDataSource,UITableViewDelegate,ChangeAlumNameDelegate,UIActionSheetDelegate>
{
    UITableView * _tableView;
    NSMutableArray * dataSource;
    
    UIButton * editBtn;
    NSMutableArray * selectedArr;
    
    UIImagePickerController * _pickerVC;

    NSString * tempDate;
}
@end

@implementation AlumContentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self main];
    //[self addBackItem];
    [self addNavgationBarwithTitle:_alumName];
    if (_isResumeAlum == YES) {
        
    }
    else
    {
        [self addRightItems];
    }
    // Do any additional setup after loading the view.
}
-(void)main
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(twoBtnSectedNotice:) name:@"twoBtnSectedNotice" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(caledarNoti:) name:@"caledarNoti" object:nil];


    dataSource = [[NSMutableArray alloc]init];
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 63, SCREEN_WIDTH, SCREEN_HEIGHT-63) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[AlumContentTableViewCell class] forCellReuseIdentifier:@"AlumContentTableViewCell"];
    [self.view addSubview:_tableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self requestDataWithdate:@""];
}
-(void)requestDataWithdate:(NSString *)date
{
    tempDate = date;
    __weak typeof(self)weakSelf = self;
    
    [U76HONet alumContentWithaction:@"" code:[Singleton share].code picsid:_alumId date:date andDataBlock:^(NSArray *arr) {
        NSLog(@"相册内容接口获取数据成功列");
        if (arr.count == 0) {
            UIView * view = (UIView *)[weakSelf.view viewWithTag:504];
            if (view) {
                [view removeFromSuperview];
            }
            [weakSelf nosearch];
        }
        else
        {
            UIView * view = (UIView *)[weakSelf.view viewWithTag:504];
            if (view) {
                [view removeFromSuperview];
            }
            if (dataSource.count!=0) {
                [dataSource removeAllObjects];
            }
            
            [dataSource addObjectsFromArray:arr];
            [_tableView reloadData];
        }
    }];
}
-(void)nosearch
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    view.backgroundColor = UIColorFromRGB(0xf1f3f2);
    view.tag = 504;
    
    UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-98/2,SIZETO6H(120), 98, 100)];
    imgV.image = [UIImage imageNamed:@"苦脸"];
    [view addSubview:imgV];
    
    UILabel * tipLab = [[UILabel alloc]initWithFrame:CGRectMake(0, imgV.bottom+SIZETO6H(20), SCREEN_WIDTH, 20)];
    tipLab.text = @"暂时没有符合条件的内容";
    tipLab.textAlignment = NSTextAlignmentCenter;
    tipLab.font = [UIFont systemFontOfSize:14];
    tipLab.textColor = UIColorFromRGB(0x333944);
    [view addSubview:tipLab];
    [self.view addSubview:view];
}
-(void)editPicsWithpid:(NSString *)pid andpname:(NSString *)pname annCount:(int)count
{
    __weak typeof(self)weakSelf = self;
    [U76HONet modifyPicsWithAction:@"" code:[Singleton share].code pid:pid pname:pname andDataBlock:^(NSDictionary *dic) {
        NSLog(@"删除图片成功了");
        if (selectedArr.count > 0) {
            int j = (int)selectedArr.count -count;
            [selectedArr removeAllObjects];
            for (int i = 0; i<j; i++) {
                [selectedArr addObject:[NSString stringWithFormat:@"0"]];
            }
        }
        
        [weakSelf requestDataWithdate:tempDate];
    }];
}
#pragma mark - _tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    AlumContentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"AlumContentTableViewCell"];
    if (dataSource.count!=0) {
        cell.model = dataSource[indexPath.row];
    }
    if (_tableView.editing == YES) {
        cell.selected = YES;
    }
    __weak typeof(self)weakSelf = self;
    [cell setCellBlock:^(PictureContentModel * model, int i) {
        if (![model.pic isEqualToString:@""]) {
            NSArray * imgUrlArr = [model.pic componentsSeparatedByString:@"|"];
            BoostViewController * boostVC = [[BoostViewController alloc]init];
            boostVC.imgArr = imgUrlArr;
            boostVC.contentStr = model.content;
            boostVC.i = i;
            [weakSelf.navigationController pushViewController:boostVC animated:YES];
        }

    }];
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (dataSource.count != 0) {
        PictureContentModel * model = dataSource[indexPath.row];
        int j = 0;
        CGFloat picWidth = (SCREEN_WIDTH - SIZETO6W(15)*2 - SIZETO6W(10)*2)/3;
        if ([model.pic isKindOfClass:[NSString class]] && ![model.pic isEqualToString:@""]) {
            NSRange range = [model.pic rangeOfString:@"|"];
            if (range.location != NSNotFound) {                NSArray * urlArr = [model.pic componentsSeparatedByString:@"|"];
                for (int i = 0; i<urlArr.count; i++) {
                    if (i%3 == 0) {
                        j++;
                    }
                }
            }
            else
            {
                j = 1;
            }
        }
        else
        {
            picWidth = 0;
        }
        CGFloat height = [model.content heightOfSize:17 width:(SCREEN_WIDTH-SIZETO6W(15)*2)];
        return j*(picWidth + SIZETO6H(10)) + height + 20 + SIZETO6H(10);
    }
    
    return 44;
    
}
//editing
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.editing) {
        return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
    }
    return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%i",(int)indexPath.row);
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        return YES;
    }
    return NO;
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"**%i",(int)indexPath.row);
    if (_tableView.editing == YES) {
        [selectedArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
    }

}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%i",(int)indexPath.row);
    if (_tableView.editing == YES) {
        [selectedArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
#pragma mark - addRightItems
-(void)addRightItems
{
    editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    editBtn.frame = CGRectMake(0, 0, 40, 40);
    [editBtn setImage:[UIImage imageNamed:@"更多"] forState:UIControlStateNormal];
    [editBtn addTarget:self action:@selector(moreAction:) forControlEvents:UIControlEventTouchUpInside];
    editBtn.tag = 711;
    UIBarButtonItem * rightItemOne = [[UIBarButtonItem alloc]initWithCustomView:editBtn];
    
    UIButton * timeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    timeBtn.frame = CGRectMake(0, 0, 40, 40);
    [timeBtn setImage:[UIImage imageNamed:@"时间"] forState:UIControlStateNormal];
    [timeBtn addTarget:self action:@selector(timeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItemTwo = [[UIBarButtonItem alloc]initWithCustomView:timeBtn];
    
    self.navigationItem.rightBarButtonItems = @[rightItemOne,rightItemTwo];
    
}
-(void)timeBtnAction:(UIButton *)btn
{
    [Singleton alertCalendar];
}
-(void)moreAction:(UIButton *)btn
{
    btn.enabled = NO;
    NSLog(@"more btn is selected");
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.2;
    view.tag = 712;
    [self.view addSubview:view];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [view addGestureRecognizer:tap];
    
    UIImageView * bgImgV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-135-20, 64, 135, 135)];
    UIImage * img = [UIImage imageNamed:@"展开窗口"];
    img = [img resizableImageWithCapInsets:UIEdgeInsetsMake(10, 30, 10, 20) resizingMode:UIImageResizingModeStretch];
    bgImgV.image = img;
    bgImgV.tag = 713;
    bgImgV.userInteractionEnabled = YES;
    bgImgV.layer.masksToBounds = YES;
    bgImgV.layer.cornerRadius = 6.0;
    [self.view addSubview:bgImgV];
    
    NSArray * titleArr = @[@"发布图片",@"管理图片",@"编辑相册"];
    NSArray * picArr = @[@"相机",@"管理图片",@"编辑-"];
    for (int i = 0; i<titleArr.count; i++) {
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, i*bgImgV.height/3, bgImgV.width, bgImgV.height/3);
        [btn setTitle:titleArr[i] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:picArr[i]] forState:UIControlStateNormal];
        [btn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
        if (i!=2) {
            UIView * lineV = [[UIView alloc]initWithFrame:CGRectMake(0, (i+1)*bgImgV.height/3, bgImgV.width, 1)];
            lineV.backgroundColor = [UIColor lightGrayColor];
            [bgImgV addSubview:lineV];
        }
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i+1;
        [bgImgV addSubview:btn];
        
    }
}
-(void)btnAction:(UIButton *)btn
{
    int tag = (int)btn.tag;
    if (tag == 1) {
        UIActionSheet * sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
        [sheet showInView:self.view];
    }
    else if (tag == 2)
    {
        [self tap];
        [self addNavgationBarwithTitle:@"管理图片"];
        UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 40, 40);
        [btn setTitle:@"全选" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(selectedAllAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:btn];
        UIButton * btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        UIBarButtonItem * rightItem2 = [[UIBarButtonItem alloc]initWithCustomView:btn2];
        
        self.navigationItem.rightBarButtonItems = @[rightItem2,rightItem];
        [_tableView setEditing:YES animated:YES];
        [_tableView reloadData];
        
        [self createDeleView];
        
        selectedArr = [[NSMutableArray alloc]init];
        for (int i = 0; i<dataSource.count; i++) {
            [selectedArr addObject:[NSString stringWithFormat:@"0"]];
        }

    }
    else if (tag == 3)
    {
        ManagerAlumViewController * managerAlumVC = [[ManagerAlumViewController alloc]init];
        managerAlumVC.alumName = _alumName;
        managerAlumVC.pid = _alumId;
        managerAlumVC.delegate = self;
        [self.navigationController pushViewController:managerAlumVC animated:YES];
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        _pickerVC = [[UIImagePickerController alloc]init];
        [_pickerVC setSourceType:UIImagePickerControllerSourceTypeCamera];
        _pickerVC.delegate = self;
        [self presentViewController:_pickerVC animated:YES completion:nil];
    }
    else if(buttonIndex == 1)
    {
//        _pickerVC = [[UIImagePickerController alloc]init];
//        [_pickerVC setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
//        _pickerVC.delegate = self;
//        [self presentViewController:_pickerVC animated:YES completion:nil];
        
        
        
        SendPictureViewController * sendPictureVC = [[SendPictureViewController alloc]init];
        sendPictureVC.sendPicture = YES;
        
        
        [self.navigationController pushViewController:sendPictureVC animated:YES];
    }
}
//将选中的图片付给头像
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * selectImg = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:nil];
    SendPictureViewController * sendpicVC = [[SendPictureViewController alloc]init];
    sendpicVC.img = selectImg;
    
    UINavigationController * SendNav = [[UINavigationController alloc]initWithRootViewController:sendpicVC];
    [self presentViewController:SendNav animated:YES completion:nil];
}

-(void)selectedAllAction:(UIButton *)btn
{
    NSLog(@"全选按钮被点击了");
//    [_tableView reloadData];
    if (btn.selected) {
        btn.selected = NO;
        for (int i = 0; i<dataSource.count; i++) {
            NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [_tableView deselectRowAtIndexPath:indexPath animated:YES];
            if (_tableView.editing == YES) {
                [selectedArr replaceObjectAtIndex:indexPath.row withObject:@"0"];
            }
        }
    }
    else
    {
        btn.selected = YES;
        
        for (int i = 0; i<dataSource.count; i++) {
            NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [_tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
            [selectedArr replaceObjectAtIndex:indexPath.row withObject:@"1"];
        }
    }
    
}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    [self tap];
}
-(void)tap
{
    NSLog(@"touch is did");
    editBtn.enabled = YES;
    UIView * view = (UIView *)[self.view viewWithTag:712];
    [view removeFromSuperview];
    
    UIImageView * imgV = (UIImageView *)[self.view viewWithTag:713];
    [imgV removeFromSuperview];
}
-(void)createDeleView
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT-90, SCREEN_WIDTH, 90)];
//    view.tag = 505;
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    
    UIButton * deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(SIZETO6W(30), 45/2, SCREEN_WIDTH-SIZETO6W(30)*2, 45);
    deleteBtn.layer.masksToBounds = YES;
    deleteBtn.layer.borderColor = [[UIColor redColor] CGColor];
    deleteBtn.layer.borderWidth = 1.0f;
    [deleteBtn setTitle:@"删除" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:deleteBtn];
    
}
-(void)deleteAction:(UIButton *)btn
{
    NSLog(@"删除按钮被点击了");
    NSLog(@"%@",selectedArr);
    NSMutableArray * mArr = [[NSMutableArray alloc]init];
    for (int i = 0; i<selectedArr.count; i++) {
        PictureContentModel * model = dataSource[i];
        if ([selectedArr[i] isEqualToString:@"1"]) {
            [mArr addObject:model];
        }
        else
        {
            
        }
    }
    
    if (mArr.count == 0) {
        
    }
    else
    {
        [Singleton alerTwoBtnMessage:@"提示" content:@"确定删除图片？删除后将无法恢复" leftBtnName:@"取消" rightBtnName:@"确认"];
        
    }
}
-(void)caledarNoti:(NSNotification *)noti
{
    NSLog(@"相册的通知接收到的消息%@",noti.object);
//    (
//     2016,
//     2,
//     21
//     )
    NSArray * arr = noti.object;
    NSMutableArray * mArr = [[NSMutableArray alloc]init];
    [mArr addObject:arr.firstObject];
    if ([[[arr objectAtIndex:1] stringValue] length]  == 1) {
        NSString *str = [NSString stringWithFormat:@"0%@",[arr objectAtIndex:1]];
        [mArr addObject:str];
    }
    else
    {
        [mArr addObject:[arr objectAtIndex:1]];
    }

    if ([[arr.lastObject stringValue] length] == 1) {
        NSString *str = [NSString stringWithFormat:@"0%@",[arr objectAtIndex:2]];
        [mArr addObject:str];
    }
    else
    {
        [mArr addObject:[arr objectAtIndex:2]];
    }
    
    NSString * timeStr = [mArr componentsJoinedByString:@""];
    NSLog(@"timeStr is %@",timeStr);
    [self requestDataWithdate:timeStr];
}
-(void)twoBtnSectedNotice:(NSNotification *)noti
{
    NSLog(@"管理图片收到了2个按钮的消息通知");
    int tempInt = [noti.object intValue];
    if (tempInt == 1) {
        
    }
    else
    {
        NSMutableArray * mArr = [[NSMutableArray alloc]init];
        for (int i = 0; i<selectedArr.count; i++) {
            PictureContentModel * model = dataSource[i];
            if ([selectedArr[i] isEqualToString:@"1"]) {
                [mArr addObject:model];
            }
            else
            {
                
            }
        }
        if (mArr.count == 1) {
            PictureContentModel * model = mArr.firstObject;
            [self editPicsWithpid:model.ids andpname:model.pic annCount:1];
        }
        else
        {
            PictureContentModel * model = mArr.firstObject;
            NSMutableString * pid = [[NSMutableString alloc]initWithString:model.ids];
            NSMutableString * pname = [[NSMutableString alloc]initWithString:model.pic];
            for (int i = 1; i<mArr.count; i++) {
                PictureContentModel * subModel = mArr[i];
                [pid appendString:[NSString stringWithFormat:@"|%@",subModel.ids]];
                [pname appendString:[NSString stringWithFormat:@"|%@",subModel.pic]];
            }
            [self editPicsWithpid:pid andpname:pname annCount:mArr.count];
        }

    }
}
-(void)changeAlumNameWithnae:(NSString *)name
{
    [self addNavgationBarwithTitle:name];
}
#pragma  mark - 返回按钮图标
-(void)addBackItem{
    UIButton * backItem = [UIButton buttonWithType:UIButtonTypeCustom];
    backItem.frame = CGRectMake(0, 0, 9, 17);
    [backItem setImage:[UIImage imageNamed:@"返回图标"] forState:UIControlStateNormal];
    [backItem addTarget:self action:@selector(backItem:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backItem];
}
-(void)backItem:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - NAVgationBarTitle
-(void)addNavgationBarwithTitle:(NSString *)title
{
    UILabel * titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 120, 30)];
    titleLab.textAlignment = NSTextAlignmentCenter;
    //    titleLab.font = HeitiFont(18);
    titleLab.text = title;
    self.navigationItem.titleView = titleLab;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
